import Koa from 'koa';
// import bodyParser from 'koa-bodyparser';
import { initialize } from './config/database';
import { redisClient } from './config/redis';
import router from './routes';
import errorMiddleware from './middlewares/error.middleware';
import staticMiddleware from './middlewares/static.middleware';
import spaMiddleware from './middlewares/spa.middleware';
import compress from 'koa-compress';
import path from 'path';
import koaBody from 'koa-body';

const uploadDir = path.join(__dirname, '../../files-temporary');
const maxFileSize = 5 * 1024 * 1024;
// const staticDir = path.join(__dirname, '../../mobile-web/dist');

const app = new Koa();

// 静态文件服务中间件
app.use(staticMiddleware);

app.use(koaBody({ multipart: true, formidable: { maxFileSize, uploadDir } }));
app.use(compress({ threshold: 1024 }));
app.use(errorMiddleware);
// app.use(bodyParser());
app.use(router.routes()).use(router.allowedMethods());

// SPA 路由处理中间件
app.use(spaMiddleware());

// 初始化数据库和Redis
Promise.all([
    initialize(),
    // Redis连接在配置文件中自动建立
]).then(([dbSuccess]) => {
    if (!dbSuccess) return;
    app.listen(3000, () => {
        console.log('服务器运行在 http://localhost:3000');
    });
}).catch(error => {
    console.error('初始化失败:', error);
});

// 优雅关闭
process.on('SIGTERM', async () => {
    console.log('正在关闭服务...');
    await redisClient.quit();
    process.exit(0);
});